package com.leetroll.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.leetroll.api.mapper.SysConfigMapper;
import com.leetroll.api.service.FileService;
import com.leetroll.api.service.SysConfigService;
import com.leetroll.common.constant.SQLConstant;
import com.leetroll.common.entity.File;
import com.leetroll.common.entity.SysConfig;
import com.leetroll.common.enums.EConfigKey;
import com.leetroll.common.utils.AliyunOSSUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SysConfigServiceImpl extends SuperServiceImpl<SysConfigMapper, SysConfig> implements SysConfigService {

    private final FileService fileService;
    @Autowired
    public SysConfigServiceImpl(FileService fileService) {
        this.fileService = fileService;
    }

    @Override
    @Cacheable(cacheNames = "listConfigFilesByKey", key = "#eConfigKey.key")
    public List<String> listConfigFilesByKey(EConfigKey eConfigKey) {
        log.info("批量获取配置数据 {}", eConfigKey.getKey());
        //查询配置表
        SysConfigServiceImpl _sysConfigServic = (SysConfigServiceImpl) AopContext.currentProxy();
        SysConfig sysConfig =  _sysConfigServic.getByKey(eConfigKey.getKey());

        //查询file表
        List<File> files = fileService.listByIdList(Arrays.stream(sysConfig.getValue().split(",")).map(Long::valueOf).collect(Collectors.toList()));

        //拼接阿里云资源访问url (public)
        return files.stream().map(file -> {
            String filePath = file.getKey() + file.getName() + "." + file.getFormat();
            return AliyunOSSUtil.GetUrl(filePath, 10);
        }).collect(Collectors.toList());
    }

    @Override
    @Cacheable(cacheNames = "getByKey", key = "#eConfigKey")
    public SysConfig getByKey(String eConfigKey) {
        log.info("查询配置 {}", eConfigKey);
        //查询配置表
        QueryWrapper<SysConfig> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(SQLConstant.SYS_CONFIG_KEY, eConfigKey);
        return this.getOne(queryWrapper);
    }

    @Override
    public String getRandomOneDefaultBg() {
        //食用动态代理获取当前类  否则缓存将失效
        SysConfigServiceImpl _sysConfigServic = (SysConfigServiceImpl) AopContext.currentProxy();
        List<String> configs = _sysConfigServic.listConfigFilesByKey(EConfigKey.DEFAULT_BG);
        return configs.get(new Random().nextInt(configs.size()));
    }
}
